/**
 *
 */
package com.zhuoyue.elmt.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.eit.eitsite.common.utils.DateUtils;
import com.eit.eitsite.modules.sys.entity.User;
import com.eit.eitsite.modules.sys.service.SystemService;
import com.eit.eitsite.modules.sys.utils.DictUtils;
import com.eit.eitsite.modules.sys.utils.UserUtils;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.zhuoyue.elmt.Constants;
import com.zhuoyue.elmt.dao.WbEmergencyHelpLogDao;
import com.zhuoyue.elmt.data.ResultData;
import com.zhuoyue.elmt.data.WbEmergencyHelpType;
import com.zhuoyue.elmt.entity.*;
import com.zhuoyue.elmt.push.PushFaultRecord;
import com.zhuoyue.elmt.service.DeviceParametersService;
import com.zhuoyue.elmt.service.GgZgdwService;
import com.zhuoyue.elmt.service.MaintenanceStaffService;
import com.zhuoyue.elmt.utils.GsonUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.eit.eitsite.common.config.Global;
import com.eit.eitsite.common.persistence.Page;
import com.eit.eitsite.common.web.BaseController;
import com.eit.eitsite.common.utils.StringUtils;
import com.zhuoyue.elmt.service.WbEmergencyHelpService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 应急救援Controller
 *
 * @author JiangYH
 * @version 2017-04-10
 */
@Controller
@RequestMapping(value = "${adminPath}/elmt/wbEmergencyHelp")
public class WbEmergencyHelpController extends BaseController {

    @Autowired
    private WbEmergencyHelpService wbEmergencyHelpService;

    @Autowired
    private MaintenanceStaffService maintenanceStaffService;

    @Autowired
    private WbEmergencyHelpLogDao wbEmergencyHelpLogDao;

    @Autowired
    private GgZgdwService ggZgdwService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private DeviceParametersService deviceParametersService;

    @ModelAttribute
    public WbEmergencyHelp get(@RequestParam(required = false) String id) {
        WbEmergencyHelp entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = wbEmergencyHelpService.get(id);
        }
        if (entity == null) {
            entity = new WbEmergencyHelp();
        }
        return entity;
    }

    @RequiresPermissions("elmt:wbEmergencyHelp:view")
    @RequestMapping(value = {"list", ""})
    public String list(WbEmergencyHelp wbEmergencyHelp, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<WbEmergencyHelp> page = wbEmergencyHelpService.findPage(new Page<WbEmergencyHelp>(request, response), wbEmergencyHelp);
        model.addAttribute("page", page);
        return "zhuoyue/elmt/wbEmergencyHelpList";
    }

    @RequiresPermissions("elmt:wbEmergencyHelp:view")
    @RequestMapping(value = "form")
    public String form(WbEmergencyHelp wbEmergencyHelp, Model model) {
        model.addAttribute("wbEmergencyHelp", wbEmergencyHelp);
        return "zhuoyue/elmt/wbEmergencyHelpForm";
    }

    @RequiresPermissions("elmt:wbEmergencyHelp:edit")
    @RequestMapping(value = "save")
    public String save(WbEmergencyHelp wbEmergencyHelp, Model model, RedirectAttributes redirectAttributes) {
        if (!beanValidator(model, wbEmergencyHelp)) {
            return form(wbEmergencyHelp, model);
        }
        wbEmergencyHelpService.save(wbEmergencyHelp);
        addMessage(redirectAttributes, "保存应急救援成功");
        return "redirect:" + Global.getAdminPath() + "/elmt/wbEmergencyHelp/?repage";
    }

    @RequiresPermissions("elmt:wbEmergencyHelp:edit")
    @RequestMapping(value = "delete")
    public String delete(WbEmergencyHelp wbEmergencyHelp, RedirectAttributes redirectAttributes) {
        wbEmergencyHelpService.delete(wbEmergencyHelp);
        addMessage(redirectAttributes, "删除应急救援成功");
        return "redirect:" + Global.getAdminPath() + "/elmt/wbEmergencyHelp/?repage";
    }


    // 1 发布救援
    @RequestMapping(value = "pubhelp")
    public String pubhelp(WbEmergencyHelp wbEmergencyHelp, HttpServletRequest request, HttpServletResponse response, Model model) {
        ResultData<List<WbEmergencyHelp>> resultData = new ResultData();
        try {
            // 写入数据
            User user = UserUtils.getUser();
            MaintenanceStaff loginMaintenanceStaff = maintenanceStaffService.getByLoginName(user.getLoginName());

            GgZgdw qryGgzgdw = new GgZgdw();
            qryGgzgdw.setZzjqdm(loginMaintenanceStaff.getMaintenanceUnitId());
            GgZgdw ggZgdw = ggZgdwService.getByCode(qryGgzgdw);

            Date curDate = new Date();
            wbEmergencyHelp.setHelpMan(user.getLoginName());
            wbEmergencyHelp.setHelpManName(loginMaintenanceStaff.getStaffName());
            wbEmergencyHelp.setHelpUnit(ggZgdw.getId());
            wbEmergencyHelp.setHelpUnitName(ggZgdw.getDwmc());
            wbEmergencyHelp.setHelpDate(curDate); // 求助时间 = 当前时间、
            wbEmergencyHelp.setHelpPhone(user.getMobile());
            wbEmergencyHelp.setStatus(Constants.WbEmergencyHelp.STATUS_PUB);
            wbEmergencyHelpService.save(wbEmergencyHelp);

            String content = "";
            content = content + "设备注册代码：" + wbEmergencyHelp.getSbzcdm();
            content = content + " 设备所在地点：" + wbEmergencyHelp.getDeviceAddr();
            content = content + " 求助人：" + wbEmergencyHelp.getHelpManName();
            content = content + " 求助时间：" + DateUtils.formatDateTime(wbEmergencyHelp.getHelpDate());
            content = content + " 求助人电话：" + wbEmergencyHelp.getHelpPhone();
            content = content + " 求助维保单位：" + wbEmergencyHelp.getHelpUnitName();

            // 进行推送
            WbEmergencyHelpType wbEmergencyHelpType = new WbEmergencyHelpType();
            BeanUtils.copyProperties(wbEmergencyHelpType, wbEmergencyHelp);
            wbEmergencyHelpType.setPushType(Constants.WbEmergencyHelp.PUSH_TYPE_PUB);

            Gson gson = GsonUtils.newInstance();
            String extrasparam = gson.toJson(wbEmergencyHelpType);

            String sbzcdm = wbEmergencyHelp.getSbzcdm();
            MaintenanceStaff qryMaintenanceStaff = new MaintenanceStaff();
            qryMaintenanceStaff.setDeviceCode(sbzcdm);
            List<MaintenanceStaff> maintenanceStaffList = maintenanceStaffService.findPushDeviceMainStaffList(qryMaintenanceStaff);

            // 推送到各个维保人员
            for (MaintenanceStaff maintenanceStaff : maintenanceStaffList) {
                // 推送号不能为空 并且 不能推送给自己
                // if (StringUtils.isNotEmpty(maintenanceStaff.getRegpushid()) && !user.getLoginName().equals(maintenanceStaff.getLoginName())) {
                if (StringUtils.isNotEmpty(maintenanceStaff.getRegpushid())) {
                    String notificationTitle = "应急救援";
                    String msgTitle = "应急救援";
                    int result = PushFaultRecord.sendToRegistrationId(maintenanceStaff.getRegpushid(), notificationTitle, msgTitle, content, extrasparam);

                    // 记录发送日志
                    WbEmergencyHelpLog wbEmergencyHelpLog = new WbEmergencyHelpLog();
                    wbEmergencyHelpLog.setRegpushid(maintenanceStaff.getRegpushid());
                    wbEmergencyHelpLog.setNotificationTitle(notificationTitle);
                    wbEmergencyHelpLog.setMsgTitle(msgTitle);
                    wbEmergencyHelpLog.setMsgContent(content);
                    wbEmergencyHelpLog.setExtrasparam(extrasparam);
                    wbEmergencyHelpLog.preInsert();
                    wbEmergencyHelpLogDao.insert(wbEmergencyHelpLog);
                    // 发送结果
                    if (result == 1) {
                    } else {
                    }
                }
            }
            // }

            List<WbEmergencyHelp> list = Lists.newArrayList();
            list.add(wbEmergencyHelp);

            resultData.setList(list);
            resultData.setCode("SUCC");
            resultData.setMessage("发布成功");
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("救援任务发布查询出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    // 2 获取救援信息 人员信息+救援信息+设备信息
    @RequestMapping(method = RequestMethod.GET, value = "/mobileget/{str}")
    public String mobileget(@PathVariable String str, HttpServletRequest request, HttpServletResponse response, Model model) {
        ResultData<List<WbEmergencyHelp>> resultData = new ResultData();
        List<WbEmergencyHelp> list = new ArrayList();
        try {
            WbEmergencyHelp wbEmergencyHelp = wbEmergencyHelpService.get(str);

            list.add(wbEmergencyHelp);
            resultData.setList(list);

            resultData.setCode("SUCC");
            resultData.setMessage("救援信息成功");
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("获取救援信息出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    // 救援任务列表 发布中
    @RequestMapping(value = "/publist")
    public String publist(WbEmergencyHelp wbEmergencyHelp, HttpServletRequest request, HttpServletResponse response, Model model) {
        ResultData<List<WbEmergencyHelp>> resultData = new ResultData();
        try {
            wbEmergencyHelp.setStatus(Constants.WbEmergencyHelp.STATUS_PUB);
            Page<WbEmergencyHelp> page = wbEmergencyHelpService.findPage(new Page<WbEmergencyHelp>(request, response), wbEmergencyHelp);
            if (null != page) {
                resultData.setList(page.getList());
            }
            resultData.setCode("SUCC");
            resultData.setMessage("救援任务列表成功");
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("救援任务列表查询出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    // 历史记录 求助记录
    @RequestMapping(value = "/helplist")
    public String helplist(WbEmergencyHelp wbEmergencyHelp, HttpServletRequest request, HttpServletResponse response, Model model) {
        ResultData<List<WbEmergencyHelp>> resultData = new ResultData();
        try {
            User user = UserUtils.getUser();
            wbEmergencyHelp.setHelpMan(user.getLoginName());
            Page<WbEmergencyHelp> page = wbEmergencyHelpService.findPage(new Page<WbEmergencyHelp>(request, response), wbEmergencyHelp);
            if (null != page) {
                resultData.setList(page.getList());
            }
            resultData.setCode("SUCC");
            resultData.setMessage("求助记录列表成功");
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("求助记录列表查询出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    // 历史记录 救援记录
    @RequestMapping(value = "/rescuelist")
    public String rescuelist(WbEmergencyHelp wbEmergencyHelp, HttpServletRequest request, HttpServletResponse response, Model model) {
        ResultData<List<WbEmergencyHelp>> resultData = new ResultData();
        try {
            User user = UserUtils.getUser();
            wbEmergencyHelp.setRescueMan(user.getLoginName());
            Page<WbEmergencyHelp> page = wbEmergencyHelpService.findPage(new Page<WbEmergencyHelp>(request, response), wbEmergencyHelp);
            if (null != page) {
                resultData.setList(page.getList());
            }
            resultData.setCode("SUCC");
            resultData.setMessage("求助记录列表成功");
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("求助记录列表查询出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    // 3 救援任务列表 - 4 历史记录
    @RequestMapping(value = "/mobilelist")
    public String mobilelist(WbEmergencyHelp wbEmergencyHelp, HttpServletRequest request, HttpServletResponse response, Model model) {
        ResultData<List<WbEmergencyHelp>> resultData = new ResultData();
        try {
            Page<WbEmergencyHelp> page = wbEmergencyHelpService.findPage(new Page<WbEmergencyHelp>(request, response), wbEmergencyHelp);
            if (null != page) {
                resultData.setList(page.getList());
            }
            resultData.setCode("SUCC");
            resultData.setMessage("列表信息成功");
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("救援任务列表查询出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    // 5 我要救援
    @RequestMapping(value = "/mobilerescue")
    public String mobilerescue(WbEmergencyHelp wbEmergencyHelp, HttpServletRequest request, HttpServletResponse response, Model model) {
        ResultData<List<WbEmergencyHelp>> resultData = new ResultData();
        try {
            List<WbEmergencyHelp> list = Lists.newArrayList();

            // 拿到救援任务信息
            WbEmergencyHelp qryWbEmergencyHelp = wbEmergencyHelpService.get(wbEmergencyHelp.getId());
            // 判断是否是发布中 才能救援
            if (Constants.WbEmergencyHelp.STATUS_PUB.equals(qryWbEmergencyHelp.getStatus())) {
                // 写入数据
                User user = UserUtils.getUser();
                MaintenanceStaff loginMaintenanceStaff = maintenanceStaffService.getByLoginName(user.getLoginName());

                GgZgdw qryGgzgdw = new GgZgdw();
                qryGgzgdw.setZzjqdm(loginMaintenanceStaff.getMaintenanceUnitId());
                GgZgdw ggZgdw = ggZgdwService.getByCode(qryGgzgdw);

                // 救援人信息
                Date curDate = new Date();
                qryWbEmergencyHelp.setRescueMan(user.getLoginName());
                qryWbEmergencyHelp.setRescueManName(loginMaintenanceStaff.getStaffName());
                qryWbEmergencyHelp.setRescueUnit(ggZgdw.getId());
                qryWbEmergencyHelp.setRescueUnitName(ggZgdw.getDwmc());
                qryWbEmergencyHelp.setResponseDate(curDate); // 应答时间 = 当前时间、
                qryWbEmergencyHelp.setRescuePhone(user.getMobile());
                qryWbEmergencyHelp.setStatus(Constants.WbEmergencyHelp.STATUS_RESCUE);
                wbEmergencyHelpService.save(qryWbEmergencyHelp);

                String content = "";
                content = content + "设备注册代码：" + qryWbEmergencyHelp.getSbzcdm();
                content = content + " 设备所在地点：" + qryWbEmergencyHelp.getDeviceAddr();
                content = content + " 救援人：" + qryWbEmergencyHelp.getRescueManName();
                content = content + " 响应时间：" + DateUtils.formatDateTime(qryWbEmergencyHelp.getResponseDate());
                content = content + " 救援人电话：" + qryWbEmergencyHelp.getRescuePhone();
                content = content + " 救援维保单位：" + qryWbEmergencyHelp.getRescueUnitName();

                // 救援人接单后进行推送通知发布人
                WbEmergencyHelpType wbEmergencyHelpType = new WbEmergencyHelpType();
                BeanUtils.copyProperties(wbEmergencyHelpType, qryWbEmergencyHelp);
                wbEmergencyHelpType.setPushType(Constants.WbEmergencyHelp.PUSH_TYPE_RESCUE);

                MaintenanceStaff maintenanceStaff = maintenanceStaffService.getByLoginName(wbEmergencyHelpType.getHelpMan());

                Gson gson = GsonUtils.newInstance();
                String extrasparam = gson.toJson(wbEmergencyHelpType);

                String notificationTitle = "应急救援";
                String msgTitle = "应急救援";
                int result = PushFaultRecord.sendToRegistrationId(maintenanceStaff.getRegpushid(), notificationTitle, msgTitle, content, extrasparam);

                // 记录发送日志
                WbEmergencyHelpLog wbEmergencyHelpLog = new WbEmergencyHelpLog();
                wbEmergencyHelpLog.setRegpushid(maintenanceStaff.getRegpushid());
                wbEmergencyHelpLog.setNotificationTitle(notificationTitle);
                wbEmergencyHelpLog.setMsgTitle(msgTitle);
                wbEmergencyHelpLog.setMsgContent(content);
                wbEmergencyHelpLog.setExtrasparam(extrasparam);
                wbEmergencyHelpLog.preInsert();
                wbEmergencyHelpLogDao.insert(wbEmergencyHelpLog);
                // 发送结果
                if (result == 1) {
                } else {
                }

                list.add(qryWbEmergencyHelp);
                resultData.setList(list);

                resultData.setCode("SUCC");
                resultData.setMessage("救援成功");
            } else {
                resultData.setCode("FAIL");
                resultData.setMessage("已有人救援");
            }
        } catch (Exception e) {
            resultData.setMessage("救援任务发布查询出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    // 6 取消救援 只能取消发布的
    @RequestMapping(value = "/mobilecancel")
    public String mobilecancel(WbEmergencyHelp wbEmergencyHelp, HttpServletRequest request, HttpServletResponse response, Model model) {
        ResultData<List<WbEmergencyHelp>> resultData = new ResultData();
        try {
            List<WbEmergencyHelp> list = Lists.newArrayList();

            // 拿到救援任务信息
            WbEmergencyHelp qryWbEmergencyHelp = wbEmergencyHelpService.get(wbEmergencyHelp.getId());
            // 判断是否是发布中 才能取消
            if (Constants.WbEmergencyHelp.STATUS_PUB.equals(qryWbEmergencyHelp.getStatus())) {
                qryWbEmergencyHelp.setStatus(Constants.WbEmergencyHelp.STATUS_CANCEL);
                qryWbEmergencyHelp.setCancelDate(new Date());
                wbEmergencyHelpService.save(qryWbEmergencyHelp);

                list.add(qryWbEmergencyHelp);
                resultData.setList(list);

                resultData.setCode("SUCC");
                resultData.setMessage("取消成功");
            } else {
                resultData.setCode("FAIL");
                resultData.setMessage("已有人救援 不能取消");
            }
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("救援任务发布查询出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    // 7 更新状态为完成 记录到达时间
    @RequestMapping(value = "/mobileupdcom")
    public String mobileupdcom(WbEmergencyHelp wbEmergencyHelp, HttpServletRequest request, HttpServletResponse response, Model model) {
        ResultData<List<WbEmergencyHelp>> resultData = new ResultData();
        try {
            List<WbEmergencyHelp> list = Lists.newArrayList();

            // 拿到救援任务信息
            WbEmergencyHelp qryWbEmergencyHelp = wbEmergencyHelpService.get(wbEmergencyHelp.getId());
            // 只能救援的状态才能设置为完成
            if (Constants.WbEmergencyHelp.STATUS_RESCUE.equals(qryWbEmergencyHelp.getStatus())) {
                qryWbEmergencyHelp.setStatus(Constants.WbEmergencyHelp.STATUS_COMPLETE);
                qryWbEmergencyHelp.setArriveDate(new Date());
                wbEmergencyHelpService.save(qryWbEmergencyHelp);

                // 到达推送
                String content = "";
                content = content + "设备注册代码：" + qryWbEmergencyHelp.getSbzcdm();
                content = content + " 设备所在地点：" + qryWbEmergencyHelp.getDeviceAddr();
                content = content + " 救援人：" + qryWbEmergencyHelp.getRescueManName();
                content = content + " 响应时间：" + DateUtils.formatDateTime(qryWbEmergencyHelp.getResponseDate());
                content = content + " 救援人电话：" + qryWbEmergencyHelp.getRescuePhone();
                content = content + " 救援维保单位：" + qryWbEmergencyHelp.getRescueUnitName();

                // 救援人接单后进行推送通知发布人
                WbEmergencyHelpType wbEmergencyHelpType = new WbEmergencyHelpType();
                BeanUtils.copyProperties(wbEmergencyHelpType, qryWbEmergencyHelp);
                wbEmergencyHelpType.setPushType(Constants.WbEmergencyHelp.PUSH_TYPE_COMPLETE);

                MaintenanceStaff maintenanceStaff = maintenanceStaffService.getByLoginName(wbEmergencyHelpType.getHelpMan());

                Gson gson = GsonUtils.newInstance();
                String extrasparam = gson.toJson(wbEmergencyHelpType);

                String notificationTitle = "应急救援";
                String msgTitle = "应急救援";
                int result = PushFaultRecord.sendToRegistrationId(maintenanceStaff.getRegpushid(), notificationTitle, msgTitle, content, extrasparam);

                // 记录发送日志
                WbEmergencyHelpLog wbEmergencyHelpLog = new WbEmergencyHelpLog();
                wbEmergencyHelpLog.setRegpushid(maintenanceStaff.getRegpushid());
                wbEmergencyHelpLog.setNotificationTitle(notificationTitle);
                wbEmergencyHelpLog.setMsgTitle(msgTitle);
                wbEmergencyHelpLog.setMsgContent(content);
                wbEmergencyHelpLog.setExtrasparam(extrasparam);
                wbEmergencyHelpLog.preInsert();
                wbEmergencyHelpLogDao.insert(wbEmergencyHelpLog);
                // 发送结果
                if (result == 1) {
                } else {
                }

                list.add(qryWbEmergencyHelp);
                resultData.setList(list);

                resultData.setCode("SUCC");
                resultData.setMessage("完成成功");
            } else {
                resultData.setCode("FAIL");
                resultData.setMessage("只能救援的状态才能设置为完成");
            }
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("救援任务发布查询出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }
}